import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/storage.js'

const Layout = () => import('@/views/myLayout.vue')
const Article = () => import('@/views/MyArticle.vue')
const Like = () => import('@/views/MyLike.vue')
const Collect = () => import('@/views/MyCollect.vue')
const User = () => import('@/views/MyUser.vue')
const Login = () => import('@/views/MyLogin.vue')
const Resgister = () => import('@/views/MyResgister.vue')

const Detail = () => import('@/views/MyDetail.vue')

Vue.use(VueRouter)

// 解决报错 此方法只针对VueRouter3.0以上
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  // return new Promise()
  // func(){} .call(this,location)
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/',
    component: Layout,
    redirect: '/article',
    children: [
      { path: 'article', component: Article },
      { path: 'like', component: Like },
      { path: 'collect', component: Collect },
      { path: 'user', component: User }

    ]
  },
  { path: '/login', component: Login },
  { path: '/register', component: Resgister },
  { path: '/article/:id', component: Detail }
]

const router = new VueRouter({
  // routes:routes
  routes
})

/// 白名单
const whitelist = ['/login', '/register']

// 路由守卫
router.beforeEach((to, from, next) => {
  // to  往哪里去 --> 到哪去的路由对象  --> /xxxx
  // console.log(to)
  // from  从哪里来 --> 从哪来的路由对象
  // next 是否放行  有没有  有效的 token
  // 请求 --> 路由-->  全局前置守卫 ----> 有token   放行
  //                             ----> 无token   ----> 是白名单  ---> 是 放行
  //                                             ----> 既没有token 又不是白名单  拦截

  const token = getToken()
  if (token) {
    next()
  } else {
    if (whitelist.includes(to.path)) {
      // 是白名单
      next()
    } else {
      console.log('拦截')
      // 拦截
      next('/login')
    }
  }
})

export default router
